package com.guli.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.guli.common.exception.NoStockException;
import com.guli.common.to.mq.OrderTo;
import com.guli.common.to.mq.SeckillOrderTo;
import com.guli.common.utils.R;
import com.guli.common.vo.MemberResponseVo;
import com.guli.gulimall.order.constant.OrderConstant;
import com.guli.gulimall.order.entity.OrderItemEntity;
import com.guli.gulimall.order.entity.PaymentInfoEntity;
import com.guli.gulimall.order.enume.OrderStatusEnum;
import com.guli.gulimall.order.feign.CartFeignService;
import com.guli.gulimall.order.feign.MemberFeignService;
import com.guli.gulimall.order.feign.ProductFeignService;
import com.guli.gulimall.order.feign.WmsFeignService;
import com.guli.gulimall.order.interceptor.LoginUserInterceptor;
import com.guli.gulimall.order.service.OrderItemService;
import com.guli.gulimall.order.service.PaymentInfoService;
import com.guli.gulimall.order.to.OrderCreateTo;
import com.guli.gulimall.order.vo.*;
//import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.gulimall.order.dao.OrderDao;
import com.guli.gulimall.order.entity.OrderEntity;
import com.guli.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WmsFeignService wmsFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberResponseVo loginUser = LoginUserInterceptor.loginUser.get();

        //异步编排，导致多线程Cookie不共享问题，解决办法：异步线程中共享主线程数据
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //共享主线程数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1.远程查询所有的收货地址列表
            List<MemberAddressVo> address = memberFeignService.getAddress(loginUser.getId());
            confirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> currentUserCartItemsFuture = CompletableFuture.runAsync(() -> {
            //共享主线程数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //2.远程查询购物车所有选中的购物项
            List<OrderItemVo> orderItemVos = cartFeignService.currentUserCartItems();
            confirmVo.setItems(orderItemVos);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = wmsFeignService.getSkusHasStock(collect);
            List<SkuStockVo> stockVos = r.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (stockVos != null && stockVos.size() > 0) {
                //库存信息
                Map<Long, Boolean> stocks = stockVos.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(stocks);
            }
        }, executor);

        //todo feign再远程调用之前要构造请求，调用很多的拦截器
        //3. 查询用户积分
        Integer integration = loginUser.getIntegration();
        confirmVo.setIntegration(integration);

        //4.其他数据自动计算

        //todo 5.防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        confirmVo.setOrderToken(token);
        //order:token:userid ，过期时间30分钟
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId(), token, 30, TimeUnit.MINUTES);
        //异步编排全部执行完成继续执行
        CompletableFuture.allOf(getAddressFuture, currentUserCartItemsFuture).get();

        return confirmVo;
    }

    //本类事务互调失效问题解决：
    @Transactional
    public void a() {
        //b,c做任何设置都没用，都是和a共用一个事务
//        this.b();//没用
//        this.c();//没用
        OrderServiceImpl orderService = (OrderServiceImpl) AopContext.currentProxy();
        orderService.b();//Propagation.REQUIRED，存在事务，就共用a事务，b事务的timeout设置不生效
        orderService.c();//Propagation.REQUIRES_NEW 新事务,不回滚
        int i = 10 / 0;
    }

    @Transactional(propagation = Propagation.REQUIRED, timeout = 2)
    public void b() {
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 20)
    public void c() {
    }

    /**
     * 本地事务：
     * ------事务特性(ACID):
     * 原子性（一组要么全部成功，要么全部失败）、
     * 一致性（银行转账金额一致性）、
     * 隔离性（多个事务是隔离的）、
     * 持久性（事务执行是持久的）
     * -------事务隔离级别：@Transactional(isolation = Isolation.READ_COMMITTED)
     * Read uncommitted：读未提交，读取未提交的数据（可能出现脏数据）
     * Read committed：读提交，默认级别，可以读取已经提交的数据（可能出现不可重复度问题，二次读取结果不同）
     * Repeatable read：可重复读，一个事务内，两次读同一条数据，结果一致，读（禁止写事务），写（禁止读写事务）
     * （可能出现幻读，指一个新增的数据被查了出来）
     * Serializable：事务串行化（无并发能力）
     * -------事务传播级别： @Transactional(propagation = Propagation.REQUIRED)
     * PROPAGATION_REQUIRED：如果存在一个事务，则支持当前事务。如果没有事务则开启一个新的事务。
     * PROPAGATION_REQUIRES_NEW:开启一个新的事务。
     * <p>
     * todo: 注意事务使用代理来实现的，代理增强的是一个service对象，那么同一个对象内事务方法互相调用默认是失败的，原因，绕过了代理对象
     * 解决方案： GulimallOrderApplication.class 写这了
     */
//    @GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo submitVo) {
        //把数据缓存到当前线程
        orderSubmitVoThreadLocal.set(submitVo);

        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        //拿到登录用户
        MemberResponseVo loginUser = LoginUserInterceptor.loginUser.get();
        //去服务器创建订单，验证令牌，验证价格，
        //1.验证令牌【令牌的对比和删除必须保证原子性】
        //redis lua脚本
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then     return redis.call('del',KEYS[1]) else     return 0 end";
        String orderToken = submitVo.getOrderToken();//传入的token
        String orderTokenKey = OrderConstant.USER_ORDER_TOKEN_PREFIX + loginUser.getId();//Redis key
        String token = redisTemplate.opsForValue().get(orderTokenKey);//服务端的token
        //lua脚本保证验证和删除原子性
        /**
         *    --验证成功就删除
         * execute(RedisScript<T> script, List<K> keys, Object... args)
         * script:脚本
         * keys：要删除的key ,List
         * args:要删除的值
         * -----
         * response： 0 - 失败； 1 - 成功
         */
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(orderTokenKey), orderToken);
        if (result == 0L) {
            //验证失败
            response.setCode(1);
            return response;
        } else {
            //验证成功
            //1.todo 创建订单信息
            OrderCreateTo order = createOrder();
            //2. todo 验价
            BigDecimal payAmount = order.getOrder().getPayAmount();//计算得来的订单价格
            BigDecimal payPrice = submitVo.getPayPrice();//前端入参价格
            //计算差价，差价小于0.01，验价成功
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //金额对比成功

                //3. todo 保存订单
                saveOrder(order);
                //4. todo 库存锁定,只要有异常，回滚订单数据
                //订单号，所有订单项（skuId，skuName,num）
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> collect = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(collect);
                /**
                 * todo  远程服务会产生分布式事务问题（网络+分布式数据库 原因，导致多数据库数据不一致性问题）
                 * 问题解决：
                 * 1. seata分布式事务
                 * 2.可靠消息+最终一致性
                 *
                 * 为了保证高并发，库存服务自己回滚。可以发消息给库存服务。
                 * 库存服务本身也可以使用自动解锁模式，那就使用消息队列来完成
                 */
                R r = wmsFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    //库存锁定成功
                    response.setOrder(order.getOrder());
                    response.setCode(0);
                    //todo 手动异常
//                    int i = 10/0;
                    //todo 订单创建成功就发送消息 mq
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return response;
                } else {
                    //库存锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            } else {
                //金额对比失败
                response.setCode(2);
                return response;
            }
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的最新的状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if (orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            //待付款状态，关单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            try {
                //订单释放，发送库存解锁消息MQ
                /**
                 * todo 如何保证消息一定会发送出去？
                 * 问题1：消息发送之前，程序挂掉了，消息丢失
                 *   解决：每一个消息都可以做好日志记录（数据库新增一张日志消息表，保存每一个消息的详细信息、状态），
                 *   定期扫描数据库,将失败的数据再次发送出去。
                 * 问题2：消息发送出去，但是未到达相应队列，服务器挂掉。消息丢失
                 *   解决：rabbitmq 消息确认机制 ，
                 *   publisher confirmCallback确认模式
                 *   publisher returnCallback 未投递到queue退回模式
                 *   consumer ack机制
                 *  问题3：消费者消费失败
                 *   解决： 手动ack模式（消费成功，手动通知清除消息）
                 *
                 *   总结：
                 *   1.做好消息确认机制（pulisher（消息状态表+confirmCallback）、consumer（手动ack） 双端确认机制）
                 *   2.每一个发送消息都在数据库做记录，定期处理失败的消息（重新发送）
                 * todo 如何防止消息重复？
                 *  问题一：业务逻辑已处理，消息ack消费之前宕机，那么这条消息就会被重复消息。
                 *   解决：
                 *   1.业务设计成幂等的，重复消费无影响
                 *   2.防重表
                 *
                 *
                 * todo 消息积压怎办？
                 *  问题一：消费者宕机
                 *  问题二：消费者消费能不足，消费者太少
                 *  问题三：流量过大
                 *   解决:
                 *      1.上线更多的消费者
                 *      2.上线专门的队列消费服务，将消息持久到数据库，然后慢慢去处理。
                 *   总结：这两种方式都要有，防止问题出现。
                 */
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception e) {
                //todo 将没法发送成功的消息进行重试发送。 发送重试保证消息发送出去
            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);

        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);//BigDecimal.ROUND_UP  保留两位小数向上取值
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());

        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
        OrderItemEntity orderItemEntity = order_sn.get(0);

        payVo.setSubject(orderItemEntity.getSkuName());
        payVo.setBody(orderItemEntity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberResponseVo member = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", member.getId())
                        .orderByDesc("id")
        );

        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);
        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo payAsyncVo) {
        //1.保存交易流水
        PaymentInfoEntity payment = new PaymentInfoEntity();
        payment.setAlipayTradeNo(payAsyncVo.getTrade_no());
        payment.setOrderSn(payAsyncVo.getOut_trade_no());
        payment.setPaymentStatus(payAsyncVo.getTrade_status());
        payment.setCallbackTime(payAsyncVo.getNotify_time());
        payment.setCreateTime(new Date());
        payment.setTotalAmount(new BigDecimal(payAsyncVo.getTotal_amount()));
        payment.setSubject("gulimall");
        paymentInfoService.save(payment);
        //2.修改订单的状态信息
        if(payAsyncVo.getTrade_status().equals("TRADE_SUCCESS") || payAsyncVo.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功状态
            String outTradeNo = payAsyncVo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo entity) {
        //todo 简写,可以补充求他数据
        //保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(entity.getOrderSn());
        orderEntity.setMemberId(entity.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //数量*单价 算出总价格
        BigDecimal multiply = entity.getSeckillPrice().multiply(new BigDecimal("" + entity.getNum()));
        orderEntity.setPayAmount(multiply);
        //保存
        this.save(orderEntity);
        //保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(entity.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        orderItemEntity.setSkuQuantity(entity.getNum());
//        productFeignService.getSpuInfoBySkuId()  todo  商品的详细信息此处省略
        //保存订单项
        orderItemService.save(orderItemEntity);
    }


    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();//订单
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();//订单项
        orderItemService.saveBatch(orderItems);
    }

    /**
     * 创建订单
     *
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        //1.创建订单
        //生成订单号
        String orderSn = IdWorker.getTimeId();
        //2.构建订单
        OrderEntity orderEntity = bulidOrder(orderSn);
        //3.获取订单项信息
        List<OrderItemEntity> orderItems = buildOrderItems(orderSn);
        //4.价格、运费、积分、优惠相关信息
        computePrice(orderEntity, orderItems);

        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItems);
        return orderCreateTo;
    }

    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItems) {
        //1.订单价格相关
        BigDecimal total = new BigDecimal("0.0");

        //优惠价格
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //成长积分
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal giowth = new BigDecimal("0.0");

        //订单的总额，叠加每一个订单项的总额
        for (OrderItemEntity entity : orderItems) {
            coupon = coupon.add(entity.getCouponAmount());//优惠券
            integration = integration.add(entity.getIntegrationAmount());//积分
            promotion = promotion.add(entity.getPromotionAmount());//打折
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));//赠送积分
            giowth = giowth.add(new BigDecimal(entity.getGiftGrowth().toString()));//赠送成长值
        }
        //总额
        orderEntity.setTotalAmount(total);
        //应付总额，实际总额+运费
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        //优惠价格
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);
        //成长值
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(giowth.intValue());
        //删除状态
        orderEntity.setDeleteStatus(0);//未删除
    }

    /**
     * 构建订单
     *
     * @return
     */
    private OrderEntity bulidOrder(String orderSn) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
        OrderEntity order = new OrderEntity();
        order.setOrderSn(orderSn);
        order.setMemberId(memberResponseVo.getId());
        order.setCreateTime(new Date());
        order.setCommentTime(new Date());
        order.setReceiveTime(new Date());
        order.setDeliveryTime(new Date());
        //2.远程获取收货地址信息
        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();
        R r = wmsFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareResp = r.getData(new TypeReference<FareVo>() {
        });
        if (fareResp != null) {
            //设置运费信息
            BigDecimal fare = fareResp.getFare();
            order.setFreightAmount(fare);
            //设置收货人信息
            order.setReceiverCity(fareResp.getAddresss().getCity());
            order.setReceiverDetailAddress(fareResp.getAddresss().getDetailAddress());
            order.setReceiverName(fareResp.getAddresss().getName());
            order.setReceiverPhone(fareResp.getAddresss().getPhone());
            order.setReceiverPostCode(fareResp.getAddresss().getPostCode());
            order.setReceiverProvince(fareResp.getAddresss().getProvince());
            order.setReceiverRegion(fareResp.getAddresss().getRegion());
        }
        //设置订单的相关状态信息
        order.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //订单自动确认收货时间，默认7天
        order.setAutoConfirmDay(7);

        return order;
    }

    /**
     * 构建所有订单项
     *
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<OrderItemVo> currentUserCartItems = cartFeignService.currentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> orderItems = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return orderItems;
        }
        return null;
    }

    /**
     * 构建单个订单项
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //1.订单信息：订单号
        //2.商品spu信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());
        //3.商品的sku信息
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        //4.优惠信息（不做）
        //5.todo 积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

        //6.订单项价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额;总额-各种优惠
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);

        return itemEntity;
    }

}